package com.example.android.jmatt.acc;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Debug;
import android.os.SystemClock;
import android.text.Spannable;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AppyActivity extends Activity {
    /** Called when the activity is first created. */
    
    private TextAppearanceSpan[] colors;
    private boolean mFirstRead = false;
    private static final String DELIMITER = " -- ";
    private ArrayList<Double> mTimes = new ArrayList<Double>();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        configureUi();
    }
    
    

    @Override
    protected void onResume() {
        super.onResume();
        Debug.startMethodTracing("/sdcard/trace_" + System.currentTimeMillis() % 1000000);
    }

    private void configureUi() {
        ((Button) findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readNextFile();
            }
        });

        ((Button) findViewById(R.id.button)).setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    mActionUpTime.add(event.getEventTime());
                    AppyActivity.this.findViewById(R.id.layout_parent).setBackgroundColor(0xFFFF0000);
                }
                return false;
            }
            
        });
        
        TextAppearanceSpan blue = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.blue), null);
        TextAppearanceSpan red = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.red), null);
        TextAppearanceSpan yellow = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.yellow), null);
        TextAppearanceSpan green = new TextAppearanceSpan("Droid Sans",
                android.R.style.TextAppearance_Medium, 30, 
                getResources().getColorStateList(R.color.green), null);
        colors = new TextAppearanceSpan[] {blue, red, yellow, blue, green, red};
        styleText();

    }
    
    private ArrayList<Long> mActionUpTime = new ArrayList<Long>();
    
    private void readNextFile() {
        TextView tv = (TextView) (findViewById(R.id.text_box));
        if (!mFirstRead) {
            tv.setText("");
            mTimes.clear();
        }
        InputStream incoming = FileReaderFactory.getNextStream();
        
        byte[] data = new byte[10 * 1024];
        int bytesRead = -1;
        // we set this to 1 since the last read will return -1
        int totalBytes = 1;
        
        //long startTime = System.currentTimeMillis();
        do {
            try {
                bytesRead = incoming.read(data);
                totalBytes += bytesRead;
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            // Log.d("JMATT", "Read " + bytesRead + " bytes out of a possible " + data.length);
        } while (bytesRead != -1);
        
        long readTime = SystemClock.uptimeMillis() - mActionUpTime.remove(0);
        if (mActionUpTime.size() == 0) {
            findViewById(R.id.layout_parent).setBackgroundColor(0xFF000000);
        }
        mFirstRead = true;

        tv.append("Delay time: " + readTime + "ms for " + (totalBytes/1024) + " KB"  + DELIMITER);
        mTimes.add(((double)readTime) / 750);
        styleText();
    }
    
    private void styleText() {
        Spannable styledText = (Spannable) ((TextView) findViewById(R.id.text_box)).getText();
        String text = styledText.toString();
        String[] words;
        if (!mFirstRead) {
            words = text.split(" ");
            for (int count = 0; count < words.length; count++) {
                mTimes.add(new Double(1));
            }
        } else {
            words = text.split(DELIMITER);
        }
        
        int position = 0;
        Iterator<Double> timeTraveler = mTimes.iterator();
        for (int count = 0; count < words.length; count++) {
            TextAppearanceSpan source = colors[count % colors.length];
            TextAppearanceSpan thisOne = new TextAppearanceSpan(source.getFamily(),
                    source.getTextStyle(), 
                    (new Double(source.getTextSize() * timeTraveler.next())).intValue(),
                    source.getTextColor(), source.getLinkTextColor());
            styledText.setSpan(thisOne, position, position + words[count].length(), 0);
            position += (words[count].length() + (mFirstRead ? DELIMITER.length() : 1));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Debug.stopMethodTracing();
    }
    
    
}